package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.ParamMissException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.sky.constant.MessageConstant.PARAMS_MISSED;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int sava(DishDTO dishDTO) {
        //1.校验数据是否合法

        //2.新增菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //保存
        int saveCnt = dishMapper.save(dish);
        //得到dishId
        Long dishId = dish.getId();
        //3.新增口味
        List<DishFlavor> flavorsList = dishDTO.getFlavors();
        if (flavorsList.size() > 0 && flavorsList != null) {
            dishMapper.saveFlavorWithDishId(flavorsList, dish.getId());
        }
        //insert into dish_flavor (dish_id,name.value) values (22,'甜度','["半糖"]')，(22,'辣度'，'["变态辣"]')
        return saveCnt;
    }

    @Override
    public PageResult findPage(DishPageQueryDTO pageQueryDTO) {
        //1.校验数据

        //2.构建分页条件
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        //3.构建查询条件
        List<DishVO> dishList = dishMapper.findPage(pageQueryDTO);
        Page<DishVO> pageData = (Page) dishList;
        //4.得到结果封装
        return new PageResult(pageData.getTotal(), pageData.getResult());
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        Dish build = dish.builder().id(id).status(status).build();
        dishMapper.updateStatus(build);
    }

    @Override
    @Transactional
    public Integer deleteByIds(List<Integer> ids) {
        //1.校验参数
        if (ids.size() <= 0) {
            throw new ParamMissException(PARAMS_MISSED);
        }
        // 2.判断是否可删除
        List<Dish> dishes = dishMapper.selectByIdsAndStatus(ids);
        if (dishes != null && dishes.size() > 0) {
            String isSaleNames = dishes.stream().map(Dish::getName).collect(Collectors.joining(","));
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE + isSaleNames);
        }
        // 3.判断是否关联
        List<Dish> dishIdList = dishMapper.selectSetmealDish(ids);
        if (dishIdList != null && dishIdList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder("这些商品在：");
            for (Dish dish : dishIdList) {
                stringBuilder.append(dish.getName() + " ");
            }
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 4.删除菜品
        Integer result = dishMapper.deleteDishByIds(ids);
        // 5.删除口味
        Integer result1 = dishMapper.deleteFlavorByIds(ids);
        return result;
    }

    @Override
    public DishVO findById(Long id) {
        DishVO dishVO = dishMapper.findByIdWithFlavors(id);
        return dishVO;
    }


    //更新菜品
    //更新口味
    @Override
    public int updateDish(DishDTO dishDTO) {
        //校验id不能为空
        Long id = dishDTO.getId();
        if (id == null) {
            throw new ParamMissException(PARAMS_MISSED);
        }
        //更新菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        int updateCount = dishMapper.updateDish(dish);

        //2.更新口味
        //2.1删除关联的口味
        dishMapper.removeRelatedFlavors(dish.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors.size() > 0 && flavors != null) {
            dishMapper.saveFlavorWithDishId(flavors, dish.getId());
        }
        return updateCount;
    }

    @Override
    public List<DishVO> findDishById(Long id) {
        List<DishVO> dishVOS=dishMapper.findDishById(id);
        return dishVOS;
    }

    /*@Override
    public List<DishVO> listDishByCategoryById(Long categoryId) {
        String key="category:"+categoryId+"dishList";
        //TODO
        log.info("查询你缓存{}中的数据",key);
        //1.根据分类ID查询该分类下的菜品列表--从缓存中查询 key避免命名冲突，导致值覆盖的问题:namespace
        List<DishVO> dishVOList=(List<DishVO>)redisTemplate.opsForValue().get(key);

        //2.如果能查到,直接返回列表
        if (dishVOList == null){
            //3.如果查不到，则查询数据库，缓存，再返回
            log.info("查询数据库中的数据并缓存");
            dishVOList = dishMapper.listDishByCategoryById(categoryId);
            redisTemplate.opsForValue().set(key,dishVOList);
        }

        return dishVOList;
*/


    @Override
    //@Cacheable(value = "category_dish", key = "#categoryId" )//#xxx 获取入参列表中值当key
    public List<DishVO> listDishByCategoryById(Long categoryId) {
        return dishMapper.listDishByCategoryById(categoryId);
    }
}



























